package com.vf.admin.client.controller.pay.newAliPay.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.controller.pay.newAliPay.AppAliPayConstants;
import com.vf.admin.client.controller.pay.newAliPay.service.AppAliPayService;
import com.vf.admin.client.dao.VipOrderDao;
import com.vf.admin.client.service.*;
import com.vf.admin.common.entity.Result;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.miaodong.service.AfterUserService;
import com.vf.admin.utils.Md5Util1;
import com.vf.admin.utils.pay.ApiAliPay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.vf.admin.common.Constants.dingdan_status_dfk;
import static com.vf.admin.common.Constants.dingdan_zhiFuLeiXing_zfb;

/**
 * <p>Title : </p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows11</p>
 *
 * @Author : zxw
 * @Date 2023/11/15 14:52
 */
@Controller
@CrossOrigin
@RequestMapping(value = "/api/new/aliPayVersion3")
public class AppAliPayController extends ClientBaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    //vip订单
    @Autowired
    private VipOrderService vipOrderService;
    @Autowired
    private PhpUserService phpUserService;
    @Autowired
    AfterUserService afterUserService;
    @Autowired
    private VipOrderDao vipOrderDao;
    @Resource
    private AppAliPayService appAliPayService;
    //用户信息
    @Autowired
    private AppUserService appUserService;
    //充值金额信息
    @Autowired
    private AppCzMoneyService appCzMoneyService;
    //会员充值金额信息
    @Autowired
    private VipPackageService vipPackageService;

    @Autowired
    private AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    private AppMingxiChongzhiService appMingxiChongzhiService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private AppPrivilegeService appPrivilegeService;
    @Autowired
    private AppInvitationRecordService appInvitationRecordService;

    //appSetup设置
    @Autowired
    private AppSetupService appSetupService;
    //钱包订单
    @Autowired
    private AppOrderService appOrderService;


    @RequestMapping(value = "/transactionsApp", method = RequestMethod.POST)
    @ResponseBody
    public Result transactionsH5(Integer type, Integer projectId, String mobileSpec, Integer userId, BigDecimal price) {

        if (type == 1) {

            //获取用户信息
            AppUser user = appUserService.get(getUserId());
            AppCzMoney appCzMoney = appCzMoneyService.get(projectId);

            String s = appAliPayService.aliPayDiamondTransactions(user, appCzMoney, mobileSpec);
            if (ObjectUtil.isEmpty(s)) {
                return this.errorJSON("充值失败，请您重新充值!");
            }
            return this.sucessJSON(s, "");
        }
        if (type == 2) {

            //获取用户信息
            AppUser user = appUserService.get(getUserId());
            VipPackage vipPackage = vipPackageService.info(projectId);

            String s = appAliPayService.aliPayVipTransactions(user, vipPackage, mobileSpec);

            if (ObjectUtil.isEmpty(s)) {
                return this.errorJSON("充值失败，请您重新充值!");
            }
            return this.sucessJSON(s, "");
        }
        if (type == 3) {
            //获取用户信息
            AppUser user = appUserService.get(getUserId());
            VipPackage vipPackage = new VipPackage();
            vipPackage.setId(1000);
            vipPackage.setPrice(new BigDecimal("28.00"));

            String s = appAliPayService.aliPayVipTransactions(user, vipPackage, mobileSpec);
            if (ObjectUtil.isEmpty(s)) {
                return this.errorJSON("充值失败，请您重新充值!");
            }
            return this.sucessJSON(s, "");
        }
        return this.errorJSON("请求参数不正确!");
    }

    /**
     * 我的钱包回调接口
     */
    @RequestMapping(value = "/diamond/AiliNotifyUrl", method = RequestMethod.POST)
    @ResponseBody
    public String diamondAiliNotifyUrl(HttpServletRequest request) throws UnsupportedEncodingException {
        //通过appId获取对应账号信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AppAliPayConstants.PUBLIC_KEY, AppAliPayConstants.CHARSET_TYPE, AppAliPayConstants.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.info("验证公钥时出现异常");
        } // 调用SDK验证签名
        logger.info("验证签名结果" + signVerified);
        //对应数据库操作
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            logger.info("-----------商户订单号" + out_trade_no);
            logger.info("-----------支付宝交易号" + trade_no);
            logger.info("-----------交易状态" + trade_status);
            //订单支付成功
            if ("TRADE_SUCCESS".equals(trade_status)) {
                //根据订单号、支付状态、支付方式获取预订单
                AppOrder topup = appOrderService.getByOrdernum(out_trade_no, dingdan_zhiFuLeiXing_zfb, dingdan_status_dfk);
                if (!StringUtils.isEmpty(topup)) {
                    AppUser user = appUserService.get(topup.getUserid());
                    //存在则更改预订单支付状态
                    appOrderService.updateStastusYzf(out_trade_no, dingdan_zhiFuLeiXing_zfb);
                    BigDecimal getDiamond = topup.getNum();
                    //添加用户钻石金额
                    appUserService.updateZuanShi(user.getId(), getDiamond);
                    //增加用户累积充值金额
                    appUserService.updateLeijiChongzhi(user.getId(), topup.getMoney());
                    //添加钻石明细
                    appMingXiZuanShiService.addMingxi(user.getId(), getDiamond, 1, "钻石充值");
                    //添加充值明细
                    appMingxiChongzhiService.addMingxi(user.getId(), getDiamond, 1, topup.getMoney(), out_trade_no, topup.getMobileSpec());
                    //完成充值任务
                    appDailyTasController.getAwardOnce(topup.getUserid(), ClientConstants.TaskOnce.RECHARGE_FIRST);
                    //如果有上级发放用户充值提成
                    addAward(topup);
                    //升级贵族
                    appPrivilegeService.isUpLevel(user);
                    logger.info("支付宝回调成功，充值入账成功");

                }
            }
        }

        return "success";
    }

    /**
     * 邀请用户充值增加父级提成
     *
     * @param order
     */
    public void addAward(AppOrder order) {
        AppInvitationRecord record = appInvitationRecordService.getShangji(order.getUserid());
        if (record != null) {
            AppSetup appSetup = appSetupService.get();
            BigDecimal divide = order.getNum().multiply(appSetup.getRechargeInvite()).setScale(2, BigDecimal.ROUND_HALF_UP);
            appUserService.addDiamonds(record.getPuserid(), divide, "邀请用户充值提成");
        }
    }

    /**
     * Vip回调接口
     */
    @RequestMapping(value = "/vip/AiliNotifyUrl", method = RequestMethod.POST)
    @ResponseBody
    public String vipAiliNotifyUrl(HttpServletRequest request) throws UnsupportedEncodingException {
        //通过appId获取对应账号信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AppAliPayConstants.PUBLIC_KEY, AppAliPayConstants.CHARSET_TYPE, AppAliPayConstants.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.info("验证公钥时出现异常");
        } // 调用SDK验证签名
        logger.info("验证签名结果" + signVerified);
        //对应数据库操作
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            logger.info("-----------商户订单号" + out_trade_no);
            logger.info("-----------支付宝交易号" + trade_no);
            logger.info("-----------交易状态" + trade_status);
            //订单支付成功
            if ("TRADE_SUCCESS".equals(trade_status)) {
                //根据订单号、支付状态、支付方式获取预订单
//                VipOrder vipOrder = vipOrderService.infoByOrderNo(out_trade_no);
                VipOrder vipOrder = vipOrderService.getByOrderNum(out_trade_no, dingdan_zhiFuLeiXing_zfb, 0);
//                if (ObjectUtil.isNotEmpty(vipOrder)
//                        && !vipOrder.getVipPackageId().equals(1000)
//                ) {
//                    //更改订单状态
//                    vipOrderService.successCall(out_trade_no);
//                } else {
//                    VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
//                    vipOrder1.setStatus(1);
//                    vipOrderDao.update(vipOrder1);
//                    //更改状态
//                    appUserService.upstateWindowTicket(vipOrder.getUserId());
//                }

                if (ObjectUtil.isNotEmpty(vipOrder)) {
                    Integer vipPackageId = vipOrder.getVipPackageId();
                    //门票
                    if (vipPackageId.equals(1000)) {

                        VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
                        vipOrder1.setStatus(1);
                        vipOrderDao.update(vipOrder1);
                        //更改状态
                        appUserService.upstateWindowTicket(vipOrder.getUserId());
                        afterUserService.upWhiteStatus(vipOrder.getUserId(), 2);
                    }
                    //会员
                    if (vipPackageId.equals(101) || vipPackageId.equals(102) || vipPackageId.equals(103)) {

                        //更改订单状态
                        vipOrderService.successCall(out_trade_no);
                        afterUserService.upWhiteStatus(vipOrder.getUserId(), 2);
                    }


                    //php

                    //4 门票
                    if (vipPackageId.equals(4)) {

                        VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
                        vipOrder1.setStatus(1);
                        vipOrderDao.update(vipOrder1);
                        //生成门票数据
                        phpUserService.callBackWindowTick(vipOrder1.getUserId());

                        //回调php


                        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中

                        Integer types = 1;

                        String param = "key:26e97719fb48687d42681b0ead73c418,uid:" + vipOrder1.getUserId() + ",money:" + vipOrder1.getPrice() + ",type:" + types;

                        String ss = Md5Util1.md5Hex(param);

                        HashMap<String, Object> paramMap = new HashMap<>();

                        paramMap.put("singer", ss);
                        paramMap.put("uid", vipOrder1.getUserId());
                        paramMap.put("money", vipOrder1.getPrice());
                        paramMap.put("type", types);
                        String result = HttpUtil.get("https://poposeapi.ptszyxx.com/apa/Shujuhaonv/play", paramMap);

                        System.out.println(result);


                    }
                    //会员  1三天  2一个月  3六个月  7 12个月
                    if (vipPackageId.equals(1) || vipPackageId.equals(2) || vipPackageId.equals(3) || vipPackageId.equals(7)) {

                        VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
                        vipOrder1.setStatus(1);
                        vipOrderDao.update(vipOrder1);
                        //生成会员数据
                        phpUserService.callBackVip(vipOrder1.getUserId(), vipPackageId);

                        Integer types = null;

                        if (vipPackageId.equals(1)) {
                            types = 2;
                        }
                        if (vipPackageId.equals(2)) {
                            types = 3;
                        }
                        if (vipPackageId.equals(3)) {
                            types = 4;
                        }
                        if (vipPackageId.equals(7)) {
                            types = 5;
                        }
                        String param = "key:26e97719fb48687d42681b0ead73c418,uid:" + vipOrder1.getUserId() + ",money:" + vipOrder1.getPrice() + ",type:" + types;

                        String ss = Md5Util1.md5Hex(param);

                        HashMap<String, Object> paramMap = new HashMap<>();

                        paramMap.put("singer", ss);
                        paramMap.put("uid", vipOrder1.getUserId());
                        paramMap.put("money", vipOrder1.getPrice());
                        paramMap.put("type", types);
                        String result = HttpUtil.get("https://poposeapi.ptszyxx.com/apa/Shujuhaonv/play", paramMap);

                        System.out.println(result);

                    }
                }
                logger.info("支付宝回调成功，充值入账成功");
            }
        }


        return "success";
    }


}
